package com.verlet.springbootdemo.simple.nettyrpc.client;

import com.verlet.springbootdemo.simple.nettyrpc.RpcResult;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentMap;

/**
 * @author verlet
 * @date 2020/4/15
 */
@Slf4j
public class RpcClientHandler extends ChannelInboundHandlerAdapter {

    /**
     * RPC调用返回的结果
     */
    private final ConcurrentMap<Long, RpcResult> concurrentMap;


    public RpcClientHandler(ConcurrentMap<Long, RpcResult> concurrentMap) {
        this.concurrentMap = concurrentMap;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcResult rpcResult = (RpcResult) msg;
        log.info( "RpcResult.RequestId={}",rpcResult.getRequestId());
        concurrentMap.put(rpcResult.getRequestId(),rpcResult);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error(cause.getMessage());
        ctx.channel().close();
    }
}
